package mall

import (
	"errors"
	"fmt"
	"github.com/jinzhu/copier"
	"mall-go-gin/global"
	"mall-go-gin/model/common"
	"mall-go-gin/model/common/enum"
	"mall-go-gin/model/mall"
	"mall-go-gin/model/mall/response"
	"mall-go-gin/model/manage"
	"mall-go-gin/model/manage/request"
	"mall-go-gin/utils"
	"time"
)

type MallOrderService struct{}

// SaveOrder 保存订单
func (m *MallOrderService) SaveOrder(token string, userAddress mall.MallUserAddress, myShoppingCartItems []response.CartItemResponse) (err error, orderNo string) {
	fmt.Println("===========SaveOrder")
	var userToken mall.MallUserToken
	err = global.GVA_DB.Where("token =?", token).First(&userToken).Error
	if err != nil {
		return errors.New("不存在的用户"), orderNo
	}
	var itemIdList []int
	var goodsIds []int
	for _, cartItem := range myShoppingCartItems {
		itemIdList = append(itemIdList, cartItem.CartItemId)
		goodsIds = append(goodsIds, cartItem.GoodsId)
	}
	var newBeeMallGoods []manage.MallGoodsInfo
	global.GVA_DB.Where("goods_id in ?", goodsIds).Find(&newBeeMallGoods)

	// 检查是否包含已下架商品
	for _, newBeeMallGood := range newBeeMallGoods {
		if newBeeMallGood.GoodsSellStatus != enum.GOODS_UNDER.Code() {
			return errors.New("已下架，无法生成订单"), orderNo
		}
	}
	newBeeMallGoodsMap := make(map[int]manage.MallGoodsInfo)
	for _, mallGood := range newBeeMallGoods {
		newBeeMallGoodsMap[mallGood.GoodsId] = mallGood
	}
	// 判断商品库
	for _, shoppingCartItemVo := range myShoppingCartItems {
		//	 查初的商品中不存在购物车中的这条关联商品数据， 直接返回错误提醒
		if _, ok := newBeeMallGoodsMap[shoppingCartItemVo.GoodsId]; !ok {
			return errors.New("购物车数据异常！"), orderNo
		}
		if shoppingCartItemVo.GoodsCount > newBeeMallGoodsMap[shoppingCartItemVo.GoodsId].StockNum {
			return errors.New("库存不足！"), orderNo
		}
	}
	fmt.Println("==========itemIdList", itemIdList)
	fmt.Println("==========goodsIds", goodsIds)
	// 删除购物车项
	if len(itemIdList) > 0 && len(goodsIds) > 0 {
		if err = global.GVA_DB.Where("cart_item_id in ?", itemIdList).Updates(mall.MallShoppingCartItem{IsDeleted: 1}).Error; err == nil {
			var stockNumDTOs []request.StockNumDTO
			copier.Copy(&stockNumDTOs, &myShoppingCartItems)
			for _, stockNumDTO := range stockNumDTOs {
				var goodsInfo manage.MallGoodsInfo
				global.GVA_DB.Where("goods_id = ?", stockNumDTO.GoodsId).First(&goodsInfo)
				err = global.GVA_DB.Where("goods_id = ? and stock_num >= ? and goods_sell_status = 0", stockNumDTO.GoodsId, stockNumDTO.GoodsCount).
					Updates(manage.MallGoodsInfo{StockNum: goodsInfo.StockNum - stockNumDTO.GoodsCount}).Error
				if err != nil {
					return errors.New("库存不足！"), orderNo
				}
			}
			// 生成订单号
			orderNo = utils.GenOrderNo()
			fmt.Println("orderNo=======", orderNo)
			priceTotal := 0
			//	 保存订单
			var newBeeMallOrder manage.MallOrder
			newBeeMallOrder.OrderNo = orderNo
			newBeeMallOrder.UserId = userToken.UserId
			//总价
			for _, newBeeMallShoppingCartItemVo := range myShoppingCartItems {
				priceTotal = priceTotal + newBeeMallShoppingCartItemVo.GoodsCount*newBeeMallShoppingCartItemVo.SellingPrice
			}
			if priceTotal < 1 {
				return errors.New("订单价格异常！"), orderNo
			}
			newBeeMallOrder.CreateTime = common.JSONTime{Time: time.Now()}
			newBeeMallOrder.UpdateTime = common.JSONTime{Time: time.Now()}
			newBeeMallOrder.TotalPrice = priceTotal
			newBeeMallOrder.ExtraInfo = ""
			// 生成订单项并保存订单项记录
			if err = global.GVA_DB.Save(&newBeeMallOrder).Error; err != nil {
				return errors.New("订单入库失败！"), orderNo
			}
			//	生成订单收获地址快照，并保存至数据库
			var newBeeMallOrederAddress mall.MallOrderAddress
			copier.Copy(&newBeeMallOrederAddress, &userAddress)
			newBeeMallOrederAddress.OrderId = newBeeMallOrder.OrderId
			//生成所有订单项快照,并保存至数据库
			var newBeeMallOrderItems []manage.MallOrderItem
			for _, newBeeMallShoppingCartItemVo := range myShoppingCartItems {
				var newBeeMallOrderItem manage.MallOrderItem
				copier.Copy(&newBeeMallOrderItem, &newBeeMallShoppingCartItemVo)
				newBeeMallOrderItem.OrderId = newBeeMallOrder.OrderId
				newBeeMallOrderItem.CreateTime = common.JSONTime{Time: time.Now()}
				newBeeMallOrderItems = append(newBeeMallOrderItems, newBeeMallOrderItem)
			}
			if err = global.GVA_DB.Save(&newBeeMallOrderItems).Error; err != nil {
				return err, orderNo
			}
		}
	}
	return
}

// MallOrderListBySearch 搜索订单
func (m *MallOrderService) MallOrderListBySearch(token string, pageNumber int, status string) (err error, list []response.MallOrderResponse, total int64) {
	fmt.Println("============MallOrderListBySearch token", token)
	var userToken mall.MallUserToken
	err = global.GVA_DB.Where("token = ?", token).First(&userToken).Error
	if err != nil {
		return errors.New("不存在的用户"), list, total
	}
	// 根据搜索条件查询
	var newBeeMallOrders []manage.MallOrder
	db := global.GVA_DB.Model(&newBeeMallOrders)
	if status != "" {
		db.Where("order_status = ?", status)
	}
	err = db.Where("user_id = ? and is_deleted = 0", userToken.UserId).Count(&total).Error
	//这里前段没有做滚动加载，直接显示全部订单
	//limit := 5
	offset := 5 * (pageNumber - 1)
	err = db.Offset(offset).Order("order_id desc").Find(&newBeeMallOrders).Error

	var orderListVOS []response.MallOrderResponse
	if total > 0 {
		//	 数据转换 将实体类转成vo
		copier.Copy(&orderListVOS, &newBeeMallOrders)
		// 设置订单状态中午显示值
		for _, orderListVO := range orderListVOS {
			_, statusStr := enum.GetNewBeeMallOrderStatusEnumByStatus(orderListVO.OrderStatus)
			orderListVO.OrderStatusString = statusStr
		}
		// 返回订单id
		var orderIds []int
		for _, order := range newBeeMallOrders {
			orderIds = append(orderIds, order.OrderId)
		}
		// 获取OrderItem
		var orderItems []manage.MallOrderItem
		if len(orderIds) > 0 {
			global.GVA_DB.Where("order_id in ?", orderIds).Find(&orderItems)
			itemByOrderIdMap := make(map[int][]manage.MallOrderItem)
			for _, orderItem := range orderItems {
				itemByOrderIdMap[orderItem.OrderId] = []manage.MallOrderItem{}
			}
			for i, itemByOrderId := range itemByOrderIdMap {
				for _, orderItem := range orderItems {
					if i == orderItem.OrderId {
						itemByOrderId = append(itemByOrderId, orderItem)
					}
					itemByOrderIdMap[i] = itemByOrderId
				}
			}
			//	封装每个订单列表的订单项数据
			for _, newBeeMallOrderListVO := range orderListVOS {
				if _, ok := itemByOrderIdMap[newBeeMallOrderListVO.OrderId]; ok {
					orderItemListTemp := itemByOrderIdMap[newBeeMallOrderListVO.OrderId]
					var newBeeMallOrderItemVOS []response.NewBeeMallOrderItemVO
					copier.Copy(&newBeeMallOrderItemVOS, &orderItemListTemp)
					newBeeMallOrderListVO.NewBeeMallOrderItemVOS = newBeeMallOrderItemVOS
					_, OrderStatusStr := enum.GetNewBeeMallOrderStatusEnumByStatus(newBeeMallOrderListVO.OrderStatus)
					newBeeMallOrderListVO.OrderStatusString = OrderStatusStr
					list = append(list, newBeeMallOrderListVO)
				}
			}
		}

	}

	return err, list, total

}

// PaySuccess 支付订单
func (m *MallOrderService) PaySuccess(orderNo string, payType int) (err error) {
	var mallOrder manage.MallOrder
	err = global.GVA_DB.Where("order_no = ? and is_deleted = 0", orderNo).First(&mallOrder).Error
	if mallOrder != (manage.MallOrder{}) {
		if mallOrder.OrderStatus != 0 {
			return errors.New("订单状态异常！")
		}
		mallOrder.OrderStatus = enum.ORDER_PAID.Code()
		mallOrder.PayType = payType
		mallOrder.PayStatus = 1
		mallOrder.PayTime = common.JSONTime{time.Now()}
		mallOrder.UpdateTime = common.JSONTime{time.Now()}
		err = global.GVA_DB.Save(&mallOrder).Error
	}
	return
}
